package DSRStructure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import reso.ip.Datagram;
import reso.ip.IPAddress;
import Message.DSRMessage;

public class RouteCache {

	private HashMap<IPAddress, ArrayList<DSRRoutingEntry>> listRoute = new HashMap<>();
	
	
	public DSRRoutingEntry lookup(IPAddress addrDest){
		ArrayList<DSRRoutingEntry> tempList = listRoute.get(addrDest);
		if((tempList == null)||(tempList.size() == 0)){
			return null;
		}else{
			DSRRoutingEntry bestEntry = tempList.get(0);
			for (DSRRoutingEntry entry : tempList) {
				if(entry.getSize() < bestEntry.getSize()){
					bestEntry= entry;
				}
			}
			return bestEntry;
		}
	}
	
	public boolean AnalyseEntry(IPAddress addr, Datagram dtgr){
		DSRMessage message = (DSRMessage) dtgr.getPayload();
		boolean modified = false;
		System.out.println("=~~=~~=~~=~~=~~=~~=~~= Analyse Start ~~=~~=~~=~~=~~=~~=~~=~~=~~");
		System.out.println("Route = " + message.getRoute());
		DSRRoutingEntry tempRoute = message.getRoute().clone();
		if(!tempRoute.contains(addr)){
			tempRoute.addAddressEntry(addr);
		}
		HashMap<IPAddress, DSRRoutingEntry> possibleRoute = tempRoute.split(addr);
		for (Entry<IPAddress, DSRRoutingEntry> values : possibleRoute.entrySet()) {
			ArrayList<DSRRoutingEntry>currRoutes = listRoute.get(values.getKey());
			boolean found = false;
			if(currRoutes != null){
				for (DSRRoutingEntry route : currRoutes) {
					           
					if(route.equals(values.getValue())){
						found = true;
					}
				}
			}
			if(!found){
				addDSRRoutingEntry(values.getKey(), values.getValue());
			}
		}
		System.out.println(listRoute);
		System.out.println("=~~=~~=~~=~~=~~=~~=~~= Analyse End ~~=~~=~~=~~=~~=~~=~~=~~=~~");
		return modified;
	}
	
	private void addDSRRoutingEntry(IPAddress  addr, DSRRoutingEntry route){
		 ArrayList<DSRRoutingEntry> tempList = listRoute.get(addr);
		 if(tempList == null){
			 tempList = new ArrayList<DSRRoutingEntry>();
		 }
		 tempList.add(route);
		 listRoute.put(addr, tempList);
		
	}
}
